package com.wxzz.elearing.comment.service.impl;

import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.wxzz.elearing.comment.dto.CommunityQuestionsAnswersDto;
import com.wxzz.elearing.comment.dto.StudyQuestionsAnswersDto;
import com.wxzz.elearing.comment.entity.ApplyStudyTitleType;
import com.wxzz.elearing.comment.entity.CommunityQuestionsAnswersList;
import com.wxzz.elearing.comment.entity.StudyQuestionsAnswersList;
import com.wxzz.elearing.comment.mapper.ApplyStudyTitleTypeMapper;
import com.wxzz.elearing.comment.mapper.CommunityQuestionsAnswersListMapper;
import com.wxzz.elearing.comment.mapper.StudyQuestionsAnswersListMapper;
import com.wxzz.elearing.comment.service.ICommunityQuestionsAnswersListService;
import com.wxzz.elearing.comment.service.IStudyQuestionsAnswersListService;
import com.wxzz.elearing.comment.service.openfeign.IWxUserApiFeign;
import com.wxzz.elearing.comment.vo.CommunityQuestionsAnswersListVo;
import com.wxzz.elearing.comment.vo.StudyQuestionsAnswersListVo;
import com.wxzz.elearning.common.dto.FeignWxUserDto;
import com.wxzz.elearning.common.vo.JgPageVo;
import com.wxzz.elearning.common.vo.ReturnVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.wxzz.elearing.comment.service.impl.CommunityGiveLikeServiceImpl.*;
import static com.wxzz.elearing.comment.service.impl.StudyGiveLikeServiceImpl.*;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author
 * @since 2021-05-14
 */
@Service
public class StudyQuestionsAnswersListServiceImpl extends ServiceImpl<StudyQuestionsAnswersListMapper, StudyQuestionsAnswersList> implements IStudyQuestionsAnswersListService {

    @Resource
    private StudyQuestionsAnswersListMapper studyQuestionsAnswersListMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    public MongoTemplate mongoTemplate;

    public ReturnVO<String> saveQuestionsAnswers(StudyQuestionsAnswersList questionsAnswersList) {
        Long publishPersonId = questionsAnswersList.getPublishPersonId();
        String publish = publishPersonId + ":Studydraft";
        if (questionsAnswersList.getIsDraft() == 1) {
            redisTemplate.opsForHash().put(STUDYDRAFTINFO, publish, JSONObject.toJSONString(questionsAnswersList));
            return new ReturnVO("草稿保存成功", questionsAnswersList.getId());
        }
        List<String> publishImageUrlList = questionsAnswersList.getPublishImageUrlList();
        String s = JSONObject.toJSONString(publishImageUrlList);
        questionsAnswersList.setPublishImageUrl(s);

        studyQuestionsAnswersListMapper.insert(questionsAnswersList);
        redisTemplate.opsForHash().delete(STUDYDRAFTINFO, publish);
        return new ReturnVO("发表文章成功", questionsAnswersList.getId());


    }

    @Autowired
    private IWxUserApiFeign iWxUserApiFeign;
    @Resource
    private ApplyStudyTitleTypeMapper applyStudyTitleTypeMapper;

    public ReturnVO<JgPageVo<List<StudyQuestionsAnswersListVo>>> queryQuestionsAnswersList(StudyQuestionsAnswersDto questionsAnswersDto) {
        Page<Object> objects = PageHelper.startPage(questionsAnswersDto.getCurPage(), questionsAnswersDto.getMaxPage());
        QueryWrapper<StudyQuestionsAnswersList> queryWrapper = new QueryWrapper();
        if(StringUtils.isNotBlank(questionsAnswersDto.getCommonlyUsed())){
            Map<String, String> map = new HashMap<>();
            ReturnVO<List<Long>> listReturnVO;
            //远程调用查询用户列表
            map.put("nickname", questionsAnswersDto.getCommonlyUsed());
            listReturnVO = iWxUserApiFeign.listWxUserByMap(map);
            //若调用方没查到数据直接返回空数组
            if (listReturnVO.getData() != null && listReturnVO.getData().size() != 0) {
                queryWrapper.like("publish_content",questionsAnswersDto.getCommonlyUsed()).or().in("publish_person_id", listReturnVO.getData());
            } else {
                queryWrapper.like("publish_content",questionsAnswersDto.getCommonlyUsed());
            }
        }
        if (StringUtils.isNotBlank(questionsAnswersDto.getPublishContent())) {
            queryWrapper.like("publish_content", questionsAnswersDto.getPublishContent() + "%");
        }
        ReturnVO<List<Long>> listReturnVO;
        Map<String, String> map = new HashMap<>();
        if (StringUtils.isNotBlank(questionsAnswersDto.getPublishPerson())) {
            //远程调用查询用户列表
            map.put("nickname", questionsAnswersDto.getPublishPerson());
            listReturnVO = iWxUserApiFeign.listWxUserByMap(map);
//            queryWrapper.eq("publish_person", questionsAnswersDto.getPublishPerson());
            //若调用方没查到数据直接返回空数组
            if (listReturnVO.getData() != null && listReturnVO.getData().size() != 0) {
                queryWrapper.in("publish_person_id", listReturnVO.getData());
            }else{
                return new ReturnVO("文章列表查询成功", new JgPageVo<>(new PageInfo(Lists.newArrayList())));
            }
        }
        if (questionsAnswersDto.getPublishPersonId() != null && questionsAnswersDto.getPublishPersonId() != 0) {
            queryWrapper.eq("publish_person_id", questionsAnswersDto.getPublishPersonId());
        }
        if (questionsAnswersDto.getEnterpriseId() != null && questionsAnswersDto.getEnterpriseId() != 0) {
            queryWrapper.eq("enterprise_id", questionsAnswersDto.getEnterpriseId());
        }
        if (questionsAnswersDto.getTitleType() != null && questionsAnswersDto.getTitleType() != 0) {
            queryWrapper.eq("title_type", questionsAnswersDto.getTitleType());
        }

        queryWrapper.orderByDesc("create_time");
        List<StudyQuestionsAnswersList> questionsAnswersListList = studyQuestionsAnswersListMapper.selectList(queryWrapper);
        ArrayList<StudyQuestionsAnswersListVo> questionsAnswersListVoArrayList = new ArrayList<>();

        questionsAnswersListList.forEach((questionsAnswersList) -> {
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(questionsAnswersList.getPublishPersonId());
            questionsAnswersList.setIcon(feignWxUserDto.getIcon());
            questionsAnswersList.setPublishPerson(feignWxUserDto.getNickname());
            String publishImageUrl = questionsAnswersList.getPublishImageUrl();
            List<String> list = JSONObject.parseObject(publishImageUrl, List.class);
            questionsAnswersList.setPublishImageUrlList(list);
            StudyQuestionsAnswersListVo temp = new StudyQuestionsAnswersListVo();
            BeanUtils.copyProperties(questionsAnswersList, temp);
            questionsAnswersListVoArrayList.add(temp);
        });

        Map<String, String> entries = redisTemplate.opsForHash().entries(STUDYGIVELIKECOUNT);
        Map<String, String> entries2 = redisTemplate.opsForHash().entries(STUDYHEATCOUNT);
        questionsAnswersListVoArrayList.forEach((questionsAnswersListVo) -> {
            String artCount = questionsAnswersListVo.getId() + ":Studycount";
            String s = entries.get(artCount);
            if (StringUtil.isNotBlank(s)) {
                int i = Integer.parseInt(s);
                questionsAnswersListVo.setGiveLikeCount(i);
            } else {
                questionsAnswersListVo.setGiveLikeCount(0);
            }
            Query query = new Query();
            query.addCriteria(Criteria.where("articleId").is(questionsAnswersListVo.getId()));
            questionsAnswersListVo.setAnswersCount(mongoTemplate.count(query, "studyCommentCollection"));

            String heatCount = questionsAnswersListVo.getId() + ":Studyheat";
            String heatNum = entries2.get(heatCount);
            if (StringUtil.isNotBlank(heatNum)) {
                int i = Integer.parseInt(heatNum);
                questionsAnswersListVo.setHeatCount(i);
            } else {
                questionsAnswersListVo.setHeatCount(0);
            }

            ApplyStudyTitleType applyStudyTitleType = applyStudyTitleTypeMapper.selectById(questionsAnswersListVo.getTitleType());
            if(applyStudyTitleType!=null){
                questionsAnswersListVo.setTitleContentText(applyStudyTitleType.getTypeName());
            }
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(questionsAnswersListVo.getPublishPersonId());
            questionsAnswersListVo.setGroup(feignWxUserDto.getOrganizationName()+"-"+feignWxUserDto.getIdentityName());
        });
        long total = objects.getTotal();
        PageInfo pageInfo = new PageInfo(questionsAnswersListVoArrayList);
        pageInfo.setTotal(total);
//        Pageable pageable = PageRequest.of(questionsAnswersDto.getCurPage(), questionsAnswersDto.getMaxPage());
        return new ReturnVO("文章列表查询成功", new JgPageVo<>(pageInfo));
    }

    public  ReturnVO<JgPageVo<List<StudyQuestionsAnswersListVo>>> adminStudyList(StudyQuestionsAnswersDto questionsAnswersDto){
        Page<Object> objects = PageHelper.startPage(questionsAnswersDto.getCurPage(), questionsAnswersDto.getMaxPage());
        QueryWrapper<StudyQuestionsAnswersList> queryWrapper = new QueryWrapper();
        if (StringUtils.isNotBlank(questionsAnswersDto.getPublishContent())) {
            queryWrapper.like("publish_content", questionsAnswersDto.getPublishContent() + "%");
        }
        if (questionsAnswersDto.getPublishPersonId() != null && questionsAnswersDto.getPublishPersonId() != 0) {
            queryWrapper.eq("publish_person_id", questionsAnswersDto.getPublishPersonId());
        }
        if (questionsAnswersDto.getEnterpriseId() != null && questionsAnswersDto.getEnterpriseId() != 0) {
            queryWrapper.eq("enterprise_id", questionsAnswersDto.getEnterpriseId());
        }
        if (questionsAnswersDto.getTitleType() != null && questionsAnswersDto.getTitleType() != 0) {
            queryWrapper.eq("title_type", questionsAnswersDto.getTitleType());
        }
        if (StringUtils.isNotBlank(questionsAnswersDto.getTitleContent())) {
            queryWrapper.like("title_content", questionsAnswersDto.getTitleContent()+"%");
        }
        queryWrapper.orderByDesc("create_time");
        List<StudyQuestionsAnswersList> questionsAnswersListList = studyQuestionsAnswersListMapper.selectList(queryWrapper);
        ArrayList<StudyQuestionsAnswersListVo> questionsAnswersListVoArrayList = new ArrayList<>();

        questionsAnswersListList.forEach((questionsAnswersList) -> {

            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(questionsAnswersList.getPublishPersonId());
            questionsAnswersList.setIcon(feignWxUserDto.getIcon());
            questionsAnswersList.setPublishPerson(feignWxUserDto.getNickname());

            String publishImageUrl = questionsAnswersList.getPublishImageUrl();
            List<String> list = JSONObject.parseObject(publishImageUrl, List.class);
            questionsAnswersList.setPublishImageUrlList(list);
            StudyQuestionsAnswersListVo temp = new StudyQuestionsAnswersListVo();
            BeanUtils.copyProperties(questionsAnswersList, temp);
            questionsAnswersListVoArrayList.add(temp);
        });

        Map<String, String> entries = redisTemplate.opsForHash().entries(STUDYGIVELIKECOUNT);
        Map<String, String> entries2 = redisTemplate.opsForHash().entries(STUDYHEATCOUNT);
        questionsAnswersListVoArrayList.forEach((questionsAnswersListVo) -> {
            String artCount = questionsAnswersListVo.getId() + ":Studycount";
            String s = entries.get(artCount);
            if (StringUtil.isNotBlank(s)) {
                int i = Integer.parseInt(s);
                questionsAnswersListVo.setGiveLikeCount(i);
            } else {
                questionsAnswersListVo.setGiveLikeCount(0);
            }
            Query query = new Query();
            query.addCriteria(Criteria.where("articleId").is(questionsAnswersListVo.getId()));
            questionsAnswersListVo.setAnswersCount(mongoTemplate.count(query, "studyCommentCollection"));

            String heatCount = questionsAnswersListVo.getId() + ":Studyheat";
            String heatNum = entries2.get(heatCount);
            if (StringUtil.isNotBlank(heatNum)) {
                int i = Integer.parseInt(heatNum);
                questionsAnswersListVo.setHeatCount(i);
            } else {
                questionsAnswersListVo.setHeatCount(0);
            }

            ApplyStudyTitleType applyStudyTitleType = applyStudyTitleTypeMapper.selectById(questionsAnswersListVo.getTitleType());
            if(applyStudyTitleType!=null){
                questionsAnswersListVo.setTitleContentText(applyStudyTitleType.getTypeName());
            }
            FeignWxUserDto feignWxUserDto = iWxUserApiFeign.selectFeignWxUserDtoByWxUserId(questionsAnswersListVo.getPublishPersonId());
            questionsAnswersListVo.setGroup(feignWxUserDto.getOrganizationName()+"-"+feignWxUserDto.getIdentityName());
        });
        long total = objects.getTotal();
        PageInfo pageInfo = new PageInfo(questionsAnswersListVoArrayList);
        pageInfo.setTotal(total);
//        Pageable pageable = PageRequest.of(questionsAnswersDto.getCurPage(), questionsAnswersDto.getMaxPage());
        return new ReturnVO("文章列表查询成功", new JgPageVo<>(pageInfo));
    }

    public ReturnVO<StudyQuestionsAnswersList> readDraft(StudyQuestionsAnswersList questionsAnswers) {
        Map<String, String> entries = redisTemplate.opsForHash().entries(STUDYDRAFTINFO);
        String draft = questionsAnswers.getPublishPersonId() + ":Studydraft";
        String str = entries.get(draft);
        JSONObject jsonObject = JSONObject.parseObject(str);
        StudyQuestionsAnswersList questionsAnswersList = JSONObject.toJavaObject(jsonObject, StudyQuestionsAnswersList.class);
        return new ReturnVO("查询草稿", questionsAnswersList);
    }
}
